package com.wyh.socket_demo.service.impl;

import com.wyh.socket_demo.service.FileStreamAdapter;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @author wyh
 * @version 1.0
 * @date 2022/4/8 16:48
 */
@Service
public class FileStreamAdapterImpl implements FileStreamAdapter {
    @Override
    public String UrlFileRead(String pdfPath) {
        try{
            URL url = new URL(pdfPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            return Base64.getEncoder().encodeToString(bytes);
            // 读取pdf文件

        }catch (Exception e){
            System.out.println(e);
        }
        return null;

    }
}
